package com.kingmed.kmss.framework.feign.client.kmcs;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kingmed.kmss.common.dto.kmcs.KmcsConsumablesDTO;
import com.kingmed.kmss.common.dto.kmcs.KmcsConsumablesQueryDTO;
import com.kingmed.kmss.common.exception.external.ExternalApiException;
import com.kingmed.kmss.common.vo.CommonPage;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class PsFeignServiceFacade {

    @Autowired
    private PsFeignService psFeignService;

    /**
     * 耗材信息列表（分页）-支持code与name查询
     */
    public CommonPage<KmcsConsumablesDTO> consumablesOr(KmcsConsumablesQueryDTO queryDTO) {
        // 首先根据name值查询（前端将值放入了name字段）
        CommonPage<KmcsConsumablesDTO> kmcsConsumablesPage = this.consumables(queryDTO);
        if (CollUtil.isEmpty(kmcsConsumablesPage.getList())) {
            // 如果根据name没有查询到值，则再根据code查
            KmcsConsumablesQueryDTO queryDTOByCode = BeanUtil.copyProperties(queryDTO, KmcsConsumablesQueryDTO.class);
            queryDTOByCode.getQuery().setMaterialCode(queryDTO.getQuery().getMaterialName());
            queryDTOByCode.getQuery().setMaterialName(null);
            kmcsConsumablesPage = this.consumables(queryDTOByCode);
        }

        return kmcsConsumablesPage;
    }

    /**
     * 耗材信息列表（分页）
     */
    public CommonPage<KmcsConsumablesDTO> consumables(KmcsConsumablesQueryDTO queryDTO) {
        CommonPage<KmcsConsumablesDTO> pageDto = new CommonPage<>();
        List<KmcsConsumablesDTO> result = new ArrayList<>();
        try {
            Response response = psFeignService.consumables(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONObject resultObj = jsonObject.getJSONObject("result");
                if (resultObj != null) {
                    String total = resultObj.getStr("totalSize");
                    pageDto.setTotal(total != null ? Long.parseLong(total) : 0L);

                    String totalPage = resultObj.getStr("totalPage");
                    pageDto.setTotalPage(totalPage != null ? Integer.parseInt(totalPage) : 0);

                    pageDto.setPageNo(Integer.parseInt(queryDTO.getPage()));
                    pageDto.setPageSize(Integer.parseInt(queryDTO.getPageSize()));
                    this.handleMp(resultObj, result);
                }
            }
            pageDto.setList(result);
            return pageDto;
        } catch (Exception e) {
            log.error("查询耗材信息列表异常：" + e.getMessage());
            throw new ExternalApiException("查询耗材信息列表异常" + e.getMessage());
        }
    }

    private void handleMp(JSONObject resultObj, List<KmcsConsumablesDTO> result) {
        JSONArray jsonArray = resultObj.getJSONArray("data");
        if (jsonArray != null) {
            jsonArray.forEach(item -> {
                KmcsConsumablesDTO mpDTO = JSONUtil.toBean(JSONUtil.toJsonStr(item), KmcsConsumablesDTO.class);
                if (mpDTO != null) {
                    result.add(mpDTO);
                }
            });
        }
    }

}
